package cn.wgspring.wedding_helper.model

import androidx.compose.runtime.mutableStateListOf
import cn.wgspring.wedding_helper.util.CSVReader
import cn.wgspring.wedding_helper.settings.StorageManager

// 购物清单列表
class WeddingShoppingList {
    // 使用可变状态列表，以便在添加、删除或修改时能够自动触发重组
    private val _items = mutableStateListOf<ShoppingItem>()
    val items: List<ShoppingItem> get() = _items
    
    // 存储时间阶段的顺序
    private val timePhaseOrder = mutableListOf<String>()
    // 存储每个时间阶段中类别的顺序
    private val categoryOrderMap = mutableMapOf<String, MutableList<String>>()
    
    // 存储管理器实例
    private val storageManager = StorageManager.getInstance()
    
    init {
        loadItems()
    }
    
    // 加载物品，优先使用本地存储数据
    private fun loadItems() {
        // 首先清空现有数据
        _items.clear()
        timePhaseOrder.clear()
        categoryOrderMap.clear()
        
        // 获取本地存储的时间阶段顺序
        val savedTimePhaseOrder = storageManager.getTimePhaseOrder()
        if (savedTimePhaseOrder.isNotEmpty()) {
            timePhaseOrder.addAll(savedTimePhaseOrder)
        }
        
        // 获取本地存储的类别顺序映射
        val savedCategoryOrderMap = storageManager.getCategoryOrderMap()
        if (savedCategoryOrderMap.isNotEmpty()) {
            savedCategoryOrderMap.forEach { (timePhase, categories) ->
                categoryOrderMap[timePhase] = categories.toMutableList()
            }
        }
        
        // 获取本地存储的所有物品
        val savedItems = storageManager.getShoppingItems()
        
        if (savedItems.isNotEmpty()) {
            // 如果本地有存储的物品，优先使用
            _items.addAll(savedItems)
            
            // 如果没有保存时间阶段顺序，从物品中提取
            if (timePhaseOrder.isEmpty()) {
                val phases = savedItems.map { it.timePhase }.distinct()
                timePhaseOrder.addAll(phases)
            }
            
            // 如果没有保存类别顺序，从物品中提取
            savedItems.forEach { item ->
                if (!categoryOrderMap.containsKey(item.timePhase)) {
                    categoryOrderMap[item.timePhase] = mutableListOf()
                }
                
                if (!categoryOrderMap[item.timePhase]!!.contains(item.category)) {
                    categoryOrderMap[item.timePhase]!!.add(item.category)
                }
            }
        } else {
            // 本地没有存储数据，加载默认数据
            loadDefaultItems()
        }
    }
    
    // 从默认数据加载物品
    private fun loadDefaultItems() {
        // 加载默认结构和时间阶段顺序
        loadDefaultStructure()
        
        // 加载默认物品
        val csvLines = CSVReader.readCSVContent(RawData.SHOPPING_LIST)
        // 跳过标题行
        if (csvLines.size > 1) {
            var currentTimePhase = ""
            var lastCategory = ""
            var nextId = 1
            
            // 从第二行开始解析数据
            for (i in 1 until csvLines.size) {
                val line = csvLines[i]
                if (line.size >= 5) {
                    // 如果第三列为空，说明这是一个时间阶段行
                    if (line[2].isBlank() && line[0].isNotBlank()) {
                        currentTimePhase = line[0]
                        lastCategory = ""
                    } else {
                        // 创建购物项
                        val purchased = line[0].trim().isNotEmpty()
                        val category = line[1].trim().takeIf { it.isNotBlank() } ?: lastCategory
                        val name = line[2].trim()
                        val quantity = line[3].trim()
                        val note = if (line.size > 4) line[4].trim() else ""
                        
                        val item = ShoppingItem(
                            id = nextId++,
                            name = name,
                            category = category,
                            timePhase = currentTimePhase,
                            quantity = quantity,
                            note = note,
                            purchased = purchased,
                        )
                        // 设置初始状态
                        item.isPurchased = purchased
                        _items.add(item)
                        
                        lastCategory = category
                    }
                }
            }
            
            // 保存导入的默认物品到本地存储
            if (_items.isNotEmpty()) {
                storageManager.saveShoppingItems(_items)
                storageManager.saveTimePhaseOrder(timePhaseOrder)
                
                // 保存类别顺序映射
                val mapToSave = categoryOrderMap.mapValues { it.value.toList() }
                storageManager.saveCategoryOrderMap(mapToSave)
            }
        }
    }
    
    // 从默认数据中加载结构，确定顺序
    private fun loadDefaultStructure() {
        val csvLines = CSVReader.readCSVContent(RawData.SHOPPING_LIST)
        // 跳过标题行
        if (csvLines.size > 1) {
            var currentTimePhase = ""
            var lastCategory = ""
            
            // 从第二行开始解析数据
            for (i in 1 until csvLines.size) {
                val line = csvLines[i]
                if (line.size >= 5) {
                    // 如果第三列为空，说明这是一个时间阶段行
                    if (line[2].isBlank() && line[0].isNotBlank()) {
                        currentTimePhase = line[0]
                        if (!timePhaseOrder.contains(currentTimePhase)) {
                            timePhaseOrder.add(currentTimePhase)
                            categoryOrderMap[currentTimePhase] = mutableListOf()
                        }
                        lastCategory = ""
                    } else if (line[2].isNotBlank()) {
                        // 处理类别
                        val category = line[1].trim().takeIf { it.isNotBlank() } ?: lastCategory
                        if (category.isNotBlank() && !categoryOrderMap[currentTimePhase]!!.contains(category)) {
                            categoryOrderMap[currentTimePhase]!!.add(category)
                        }
                        lastCategory = category
                    }
                }
            }
        }
    }
    
    // 获取按时间阶段分组的购物清单项
    fun getItemsByTimePhase(): Map<String, List<ShoppingItem>> {
        // 分组物品
        val groupedItems = items.groupBy { it.timePhase }
        
        // 创建一个有序的LinkedHashMap，保持时间阶段的顺序
        val orderedResult = linkedMapOf<String, List<ShoppingItem>>()
        
        // 按照timePhaseOrder的顺序添加物品组
        timePhaseOrder.forEach { timePhase ->
            groupedItems[timePhase]?.let { phaseItems ->
                orderedResult[timePhase] = phaseItems
            }
        }
        
        // 添加任何可能没有在预定义顺序中的时间阶段（以防万一）
        groupedItems.keys.forEach { timePhase ->
            if (!orderedResult.containsKey(timePhase)) {
                orderedResult[timePhase] = groupedItems[timePhase]!!
            }
        }
        
        return orderedResult
    }
    
    // 获取某个时间阶段内按类别分组的购物清单项
    fun getItemsByCategoryInTimePhase(timePhase: String, items: List<ShoppingItem>): Map<String, List<ShoppingItem>> {
        // 分组物品
        val groupedItems = items.groupBy { it.category }
        
        // 创建一个有序的LinkedHashMap，保持类别的顺序
        val orderedResult = linkedMapOf<String, List<ShoppingItem>>()
        
        // 获取该时间阶段的类别顺序
        val categoryOrder = categoryOrderMap[timePhase] ?: return groupedItems
        
        // 按照categoryOrder的顺序添加物品组
        categoryOrder.forEach { category ->
            groupedItems[category]?.let { categoryItems ->
                orderedResult[category] = categoryItems
            }
        }
        
        // 添加任何可能没有在预定义顺序中的类别（以防万一）
        groupedItems.keys.forEach { category ->
            if (!orderedResult.containsKey(category)) {
                orderedResult[category] = groupedItems[category]!!
            }
        }
        
        return orderedResult
    }
    
    // 添加新物品
    fun addItem(item: ShoppingItem) {
        // 如果时间阶段不在列表中，添加它
        if (!timePhaseOrder.contains(item.timePhase)) {
            timePhaseOrder.add(item.timePhase)
            categoryOrderMap[item.timePhase] = mutableListOf()
            
            // 保存更新后的时间阶段顺序
            storageManager.saveTimePhaseOrder(timePhaseOrder)
        }
        
        // 如果类别不在该时间阶段的已知类别中，添加它
        if (!categoryOrderMap[item.timePhase]!!.contains(item.category)) {
            categoryOrderMap[item.timePhase]!!.add(item.category)
            
            // 保存更新后的类别顺序映射
            val mapToSave = categoryOrderMap.mapValues { it.value.toList() }
            storageManager.saveCategoryOrderMap(mapToSave)
        }
        
        // 添加到本地存储并获取带ID的物品
        val savedItem = storageManager.addShoppingItem(item)
        _items.add(savedItem)
    }
    
    // 删除物品
    fun removeItem(item: ShoppingItem) {
        // 标记物品为已删除
        if (item.id > 0) {
            storageManager.markShoppingItemAsDeleted(item.id)
        }
        
        // 从当前列表中删除
        _items.remove(item)
    }
    
    // 更新物品信息
    fun updateItem(oldItem: ShoppingItem, newName: String, newCategory: String, newQuantity: String, newNote: String) {
        val index = _items.indexOf(oldItem)
        if (index != -1) {
            // 如果类别已改变
            if (oldItem.category != newCategory) {
                // 如果新类别不在该时间阶段的已知类别中，添加它
                if (!categoryOrderMap[oldItem.timePhase]!!.contains(newCategory)) {
                    categoryOrderMap[oldItem.timePhase]!!.add(newCategory)
                    
                    // 保存更新后的类别顺序映射
                    val mapToSave = categoryOrderMap.mapValues { it.value.toList() }
                    storageManager.saveCategoryOrderMap(mapToSave)
                }
            }
            
            // 创建一个新的物品对象，保留原有的ID和时间段，更新类别
            val newItem = ShoppingItem(
                id = oldItem.id,
                name = newName,
                category = newCategory,
                timePhase = oldItem.timePhase,
                quantity = newQuantity,
                note = newNote,
                purchased = oldItem.isPurchased,
            )
            
            // 保存到本地存储
            val updatedItem = storageManager.updateShoppingItem(newItem)
            
            // 替换原有物品
            _items[index] = updatedItem
        }
    }
    
    // 保留旧的方法以保持兼容性
    fun updateItem(oldItem: ShoppingItem, newName: String, newQuantity: String, newNote: String) {
        updateItem(oldItem, newName, oldItem.category, newQuantity, newNote)
    }
    
    // 切换物品的购买状态
    fun toggleItemPurchased(item: ShoppingItem) {
        val newState = !item.isPurchased
        item.isPurchased = newState
        
        // 保存状态到本地存储
        if (item.id > 0) {
            storageManager.saveShoppingItemState(item.id, newState)
        }
    }
}